package org.sky.wall.visual.ui

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.TextureView
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.CameraSelector
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import com.google.common.util.concurrent.ListenableFuture
import org.sky.wall.visual.R
import org.sky.wall.visual.databinding.ActivityPreviewBinding
import org.sky.wall.visual.util.CameraLiveWallpaper
import org.sky.wall.visual.util.PermissionUtil
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

class PreviewActivity : AppCompatActivity(),PermissionUtil.PermissionCallback {
	private lateinit var bin: ActivityPreviewBinding
	private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>
	
	
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		bin = ActivityPreviewBinding.inflate(layoutInflater)
		setContentView(bin.root)
		cameraProviderFuture = ProcessCameraProvider.getInstance(this)
		PermissionUtil.initPermission(this,this)
	}
	override fun onPermissionGranted() {
		bin.info.setOnClickListener {
			Intent(this@PreviewActivity,ExplainActivity::class.java).also {
				startActivity(it)
			}
		}
		cameraProviderFuture.addListener({
			val cameraProvider = cameraProviderFuture.get()
			bindPreview(cameraProvider)
		}, ContextCompat.getMainExecutor(this))
		
		bin.setting.setOnClickListener {
			startService(Intent(this, CameraLiveWallpaper::class.java))
			val pickWallpaper = Intent(Intent.ACTION_SET_WALLPAPER)
			val chooser = Intent.createChooser(pickWallpaper, getString(R.string.choose_wallpaper))
			startActivity(chooser)
			finish()
		}
	}
	private fun bindPreview(cameraProvider : ProcessCameraProvider) {
		var preview : Preview = Preview.Builder()
			.build()
		var cameraSelector : CameraSelector = CameraSelector.Builder()
			.requireLensFacing(CameraSelector.LENS_FACING_BACK)
			.build()
		
		preview.setSurfaceProvider(bin.viewFinder.surfaceProvider)
		
		var camera = cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview)
	}
}
